package so.sao.shop.supplier.auth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;
import so.sao.shop.supplier.dao.authorized.PermissionDao;
import so.sao.shop.supplier.domain.authorized.Permission;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 加载权限到map, 后续判断请求url是否在map中,在则调用decide判断是否有权，否则放行
 *
 * @author
 * @create 2017-07-08 21:54
 **/
@Service
public class SecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private PermissionDao permissionDao;

    private Map<String, Collection<ConfigAttribute>> map = null;

    /**
     * 加载权限表中所有权限 该方法薛承城重写
     */
    public void loadResourceDefine() {
        map = new HashMap<>();
        //Collection<ConfigAttribute> array;
        ConfigAttribute cfg;
        List<Permission> permissions = permissionDao.findAll();
        for (Permission permission:permissions) {
        	String apiUrl = permission.getApiUrl();
        	//权限类型为44表示不用做权限拦截
        	if(apiUrl == null || "".equals(apiUrl) || permission.getType() == 44) {
        		continue ;
        	}
            cfg = new SecurityConfig(permission.getCode());
            Collection<ConfigAttribute> configAttributes = map.get(apiUrl);
        	if(configAttributes == null || configAttributes.size() <= 0) {
                configAttributes = new ArrayList<>();
                configAttributes.add(cfg);
            } else {
                configAttributes.add(cfg);
            }
            //array = new ArrayList<>();

            //此处只添加了用户的名字，其实还可以添加更多权限的信息，例如请求方法到ConfigAttribute的集合中去。此处添加的信息将会作为MyAccessDecisionManager类的decide的第三个参数。
            //array.add(cfg);
            //用权限的getUrl() 作为map的key，用ConfigAttribute的集合作为 value，
            map.put(apiUrl, configAttributes);
        }
    }

    /**
     * 此方法是为了判定用户请求的url 是否在权限表中，如果在权限表中，则返回给 decide 方法，用来判定用户是否有此权限。如果不在权限表中则放行。
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        if (map == null) loadResourceDefine();
        //object 中包含用户请求的request 信息
        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
        AntPathRequestMatcher matcher;
        String resUrl;
        for (Iterator<String> iter = map.keySet().iterator(); iter.hasNext(); ) {
            resUrl = iter.next();
            matcher = new AntPathRequestMatcher(resUrl);
            //OPTIONS不拦截
            if (!HttpMethod.OPTIONS.matches(request.getMethod())&&matcher.matches(request)) {
                return map.get(resUrl);
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}